package com.aldobucchi.x.mx.core.Container
{
	import mx.core.UIComponent;
	import mx.core.Container;
	
	
	/**
	 * 
	 * @author aldo.bucchi@gmail.com
	 * 
	 */	
	public class ContainerUtil
	{
		
		
		
		/**
		 * 
		 * @param container
		 * @param index1
		 * @param index2
		 * @return 
		 * 
		 */		
		public static function swapChildrenAt( container:Container, index1:int, index2:int ):Boolean
		{
			// check bounds
			if ( index1 >= container.numChildren ) return false;
			if ( index2 >= container.numChildren ) return false;
			
			if ( index1 == index2 ) return true;
			
			var child1:UIComponent = container.getChildAt( index1 ) as UIComponent;
			var child2:UIComponent = container.getChildAt( index2 ) as UIComponent;
			
			container.removeChild( child1 );
			container.removeChild( child2 );
			
			if ( index1 < index2 ) // the order is important... some indexes will be incremented when the first value gets added
			{
				container.addChildAt( child2, index1 );				
				container.addChildAt( child1, index2 );				
			}
			else
			{
				container.addChildAt( child1, index2 );				
				container.addChildAt( child2, index1 );				
			}
			
			return true;								
		}
		
		
		
		/**
		 * 
		 * @param container
		 * @param child1
		 * @param child2
		 * @return 
		 * 
		 */		
		public static function swapChildren( container:Container, child1:UIComponent, child2:UIComponent ):Boolean
		{
			if ( ! container.contains( child1 ) ) return false;
			if ( ! container.contains( child2 ) ) return false;

			return swapChildrenAt( container, container.getChildIndex( child1 ), container.getChildIndex( child2 ) );

		}
		
	}

}

/*
Gordon Smith on swapChildren ( from a flexcoders thread )

You say your container is a DisplayObjectContainer.
Is it also a Flex Container such as Canvas or VBox?
If so, there is a bug with using swapChildrenAt() and maybe with swapChildren() as well.
Try using removeChildAt() and addChildAt() instead.
 
A Flex Container does tricky stuff with child indexes and overrides 
child management APIs such as numChildren, addChildAt(), removeChildAt(), etc.
because there are two kinds of children -- content children and non-content children. If you write
 
<HBox>
    <Button/>
    <Button/>
</HBox>
 
there are only two content children but,
if the HBox has a background or scrollbars,
there can be additional non-children children.
 
I think what happened is that the swapChildren() and swapChildrenAt() methods 
got added to DisplayObjectContainer in Player 9, 
and the Flex framework is not yet supporting them properly in the Container class.
 
- Gordon */